#!/bin/bash
BASE_DIR=/usr/local/ca
RSA_BITS_NUM=4096
VALID_DAYS=3650
PASSWD=801125




#创建CA私钥和CA公钥
openssl genrsa -aes256 -passout pass:$PASSWD -out ca-key.pem 4096

openssl req -new -x509 -days 3650 -key ca-key.pem -sha256 -out ca.pem \
    -subj "/C=CN/ST=Liaoning/L=Dalian/O=52dot/OU=software/CN=192.168.250.6"
    
#生成server-key.pem
openssl genrsa -out server-key.pem 4096

#用CA签署公钥
openssl req -subj "/CN=192.168.250.6" -sha256 -new -key server-key.pem -out server.csr

#设置访问权限
echo subjectAltName = DNS:192.168.250.6,IP:0.0.0.0 >> extfile.cnf
#DNS为docker 服务器IP,IP为允许访问的IP,0.0.0.0为不限制,多IP可以用
echo extendedKeyUsage = serverAuth >> extfile.cnf

#生成签名证书
openssl x509 -req -days 3650 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out server-cert.pem -extfile extfile.cnf
  
#生成客户端key.pem
openssl genrsa -out key.pem 4096

openssl req -subj '/CN=client' -new -key key.pem -out client.csr

#用秘钥做客户端身份验证
echo extendedKeyUsage = clientAuth >> extfile.cnf
echo extendedKeyUsage = clientAuth > extfile-client.cnf

#生成客户端签名证书
openssl x509 -req -days 3650 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out cert.pem -extfile extfile-client.cnf

#删除无用文件
rm -v client.csr server.csr extfile.cnf extfile-client.cnf
#修改权限
chmod -v 0400 ca-key.pem key.pem server-key.pem
chmod -v 0444 ca.pem server-cert.pem cert.pem

#复制证书到docker配置目录
cp server-*.pem /etc/docker/
cp ca.pem /etc/docker/

#修改docker启动文件
vi /lib/systemd/system/docker.service
#把
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
#更改为
ExecStart=/usr/bin/dockerd --tlsverify --tlscacert=/usr/local/ca/ca.pem --tlscert=/usr/local/ca/server-cert.pem --tlskey=/usr/local/ca/server-key.pem -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock

#或者改/etc/docker/daemon.json
#增加如下内容
{
  "tlsverify": true,
  "tlscert": "/var/docker/server-cert.pem",
  "tlskey": "/var/docker/server-key.pem",
  "tlscacert": "/var/docker/ca.pem",
  "hosts": [
    "tcp://0.0.0.0:2376",
    "unix:///var/run/docker.sock"
  ]
}

#复制证书到本地目录(ca-key.pem,ca.pem,cert.pem,key.pem)
#设置idea 在docker设置用tcp socket ,url用https:/域名或IP:2375,证书目录设置成把上面文件复制到的目录

